import { Service } from "egg";
import { userProps } from "app/model/user";

export default class UserService extends Service {
  /**
   * 创建用户
   */
  public async createUserByEmail(payload: userProps) {
    const { ctx } = this;
    const { username, password } = payload;
    const hash = await ctx.genHash(password as string);
    const userCreateData: Partial<userProps> = {
      username,
      password: hash,
      email: username,
    };
    return this.app.model.User.create(userCreateData);
  }
  public async createUserByPhone(payload: userProps) {
    const { phoneNumber } = payload;
    const userCreateData: Partial<userProps> = {
      username: phoneNumber,
      phoneNumber,
      type: "cellphone",
      nickname: `乐高${phoneNumber?.slice(-4)}`,
    };
    return this.app.model.User.create(userCreateData);
  }
  async findById(id: string) {
    let result = this.app.model.User.findById(id);
    return result;
  }
  async findByUsername(username: string) {
    const result = this.app.model.User.findOne({ username });
    return result;
  }
  async findByPhoneNumber(phoneNumber: string) {
    const result = this.app.model.User.findOne({ phoneNumber });
    return result;
  }
  //获取gitee的access_token
  async getAcessToken(code: string) {
    const { ctx, app } = this;
    const { cid, secret, authUrl } = app.config.giteeOauthConfig;
    //发送请求
    const result = await ctx.curl(authUrl, {
      method: "POST",
      contentType: "application/json",
      dataType: "json",
      data: {
        client_id: cid,
        client_secret: secret,
        code,
        redirect_uri: "http://localhost:7001/api/user/gitee/callback",
        grant_type: "authorization_code",
      },
    });
    return result.data;
  }
  //通过access_token获取gitee用户信息
  async getUserInfoByAccessToken(access_token: string) {
    const { ctx } = this;
    try {
      //发送请求
      const result = await ctx.curl(
        `https://gitee.com/api/v5/user?access_token=${access_token}`,
        {
          method: "GET",
          contentType: "application/json",
          dataType: "json",
        }
      );
      return result.data;
    } catch (error) {
      ctx.logger.error("gitee result", error);
      throw new Error("gitee请求失败");
    }
  }
  //通过gitee用户信息创建用户并且登录
  async loginByGitee(code: string) {
    const { app } = this;
    const {access_token} = await this.getAcessToken(code);
    const { name, avatar_url, email, id } = await this.getUserInfoByAccessToken(
      access_token
    );
    //是否存在
    const user = await this.findByUsername(`gitee${id}`);

    if (user) {
      const token = await app.jwt.sign(
        { username: user.username },
        app.config.jwt.secret,
        { expiresIn: "1d" }
      );
      return token;
    } else {
      const userData = await app.model.User.create({
        username: "gitee" + id,
        nickname: name,
        picure: avatar_url,
        email:email??"",
        oauthId: id,
        type: "oauth",
        provider: "gitee",
      });
      const token = await app.jwt.sign(
        { username: userData.username },
        app.config.jwt.secret,
        { expiresIn: "1d" }
      );
      return token;
    }
  }
}
